<?php
/**
 * 
 * @author huangyusheng
 * @since 2014-3-20
 * @package project_name.package_name
 */
class Pfinal_Plugin_ActiveRecord implements Pfinal_Plugin_Interface {
	
	protected $dataSourceTable;
	
	/**
	 * 
	 * @var Pfinal_Plugin_Orm_Entity
	 */
	protected $ormMapping;
	
	/**
	 * 添加一组<数据源名称,数据源adapter>
	 * @param unknown_type $sourceName
	 * @param unknown_type $connectionPlugin
	 */
	public function add($sourceName,Pfinal_Plugin_DbConnection $connectionPlugin){
		$this->dataSourceTable[$sourceName] = $connectionPlugin;
	}
	
	/**
	 * 添加自动注入的table到entity的依赖注入类，返回一个entity实体
	 * @param unknown_type $schema
	 * @param Pfinal_Plugin_Orm_Kit $ormClass
	 */
	public function addOrmMapping($tablename,$entity){
		$this->ormMapping[$tablename] = new Pfinal_Plugin_Orm_Kit($entity);
	}
	
	/**
	 * 
	 * @param unknown_type $dataset
	 */
	public function buildEntity($tablename,$dataset){
		$entityKit = $this->ormMapping[$tablename];
		if (null===$entityKit) {
			throw new Pfinal_Exception_Runtime("undefined entity for {$tablename}");
		}
		$ret = array();
		if (!empty($dataset)){
			foreach ($dataset as $row){
				$ret[] = $entityKit->build($row);
			}
		}
		return $ret;
	}
	
	
	/**
	 * @return the $dataSourceTable
	 */
	public function getDataSource($name=null) {
		if (is_null($name)){
			if (!empty($this->dataSourceTable)){
				return end($this->dataSourceTable);
			}else{
				throw new Pfinal_Exception_Runtime("no default datasource found!");
			}
		}
		if (isset($this->dataSourceTable[$name])){
			return $this->dataSourceTable[$name];
		}else{
			throw new Pfinal_Exception_Runtime("can not find datasource by name {$name}");
		}
	}
	

	/*
	 * (non-PHPdoc) @see Pfinal_Plugin_Interface::start()
	 */
	public function start() {
		// TODO Auto-generated method stub
	}
	
	/*
	 * (non-PHPdoc) @see Pfinal_Plugin_Interface::stop()
	 */
	public function stop() {
		// TODO Auto-generated method stub
	}
	
	// TODO - Insert your code here
}

?>